#include "qdlggchat.h"
#include "ui_qdlggchat.h"

//add by dimon, 2024-03-17 11:48
#include "common.h"
#include <QMessageBox>
#include <QColorDialog>
#include "qmsg.h"
#include <QDateTime>


//QDlgGChat::QDlgGChat(QWidget *parent)
QDlgGChat::QDlgGChat(quint32 userId, QString ip, QString port, QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::QDlgGChat)
{
    ui->setupUi(this);
}

QDlgGChat::~QDlgGChat()
{
    delete ui;
}

//add by dimon, 2024-03-17 11:48
//初始化
void QDlgGChat::init(){
    QMsg msg;
    msg.type = MSG_CLIENT_CONN;
    msg.senderID = userid;
    msg.tarIP = QHostAddress(ip).toIPv4Address();
    msg.tarPort = (quint16)port.toUInt()+1;
    udpSocekt.sendMsg(&msg);

    //信号-槽 关联
    connect(&udpSocekt, SIGNAL(readReady), this, SLOT(recvMsg));
}

//接收消息
void QDlgGChat::recvMsg(){
    QByteArray block;
    quint8 msgType;
    quint16  size;
    QHostAddress peerIP;
    quint16 peerPort;

    //设置Block byteArry字节数组的大小size和 UDP socket套接字的缓存区一致
    block.resize(udpSocekt.pendingDatagramSize());

    //UDP 接受数据到 byteArray 字节数组
    this->udpSocekt.readDatagram(block.data(), block.size(), &peerIP, &peerPort);

    //从byteArray字节数组提取数据
    //从byteArray创建 DataStream数据流，只读
    QDataStream in(&block, QIODevice::ReadOnly);
    //从数据流QDataStram提取数据
    //'>>'提取运算符从数据流提取数据
    in >> size >> msgType;


    switch(msgType){

    case MSG_SERVER_USER_ONLINE:  //用户上线
    {
        QList<quint32> listUserid;
        QStringList listName;
        in >> listUserid >> listName;
        ui->listUser->clear();
        for(int i = 0; i<listUserid.count(); i++){
            QString itemString;
            itemString = listName.at(i) + "[" + QString::number((listUserid.at(i))) + "]";
            ui->listUser->addItem(itemString);
        }
        ui->labelCount->setText(QString::number(ui->listUser->count()) + "个用户在线");
        break;
    }
    case MSG_CLIENT_GROUP_CHAT: //群聊消息
    {
        QString time = QDateTime::currentDateTime().toString("yyyy--MM-dd hh:mm:ss");

        quint32 peerId;
        QString peerName, word;
        in >> peerId >> peerName >> word;
        QString strInfo = peerName + "(" + QString::number(peerId) + ")" + time;

        if(peerId == userid){
            ui->txtbrosRecv->setTextColor(Qt::gray);
        }
        else{
            ui->txtbrosRecv->setTextColor(Qt::blue);
        }
        ui->txtbrosRecv->setCurrentFont(QFont("Times New Roman", 12));
        ui->txtbrosRecv->append(strInfo);
        ui->txtbrosRecv->append(word);
        break;
    }
    case MSG_SERVER_CHANGE_USER_STATUS: //有新用户登陆
    {
        quint32 peerId;
        QString peerName;
        in >> peerId >> peerName;
        if(this->userid != peerId){ //如果登陆的不是自己
            QString newItem;
            newItem.append(peerName + "[" + peerId + "]");
            for(int i=0; i<ui->listUser->count(); i++){ //如果该用户已在列表
                if(ui->listUser->item(i)->text() == newItem){
                    delete ui->listUser->takeItem(i);
                }
            }
            ui->listUser->addItem(newItem); //将该用户加入用户列表
            ui->labelCount->setText(QString::number(ui->listUser->count()) + "个用户在线");
        }
    }
    case MSG_CLIENT_LOGOUT:
    {
        quint32 peerId;
        QString peerName;
        in >> peerId >> peerName;

        QString newItem;
        newItem.append(peerName + "[" + peerId + "]");
        for(int i=0; i<ui->listUser->count(); i++){//如果该用户已经在列表，则删除
            if(ui->listUser->item(i)->text() == newItem){
                delete ui->listUser->takeItem(i);
            }
        }

        ui->labelCount->setText(QString::number(ui->listUser->count()) + "个用户在线");
        break;
    }
    default:
        break;
    }
}

//如果修改了‘font 格式’后，重新设置工具栏中  'font' 按钮的状态
void QDlgGChat::currentFromatChanged(const QTextCharFormat &format){
    ui->coboxFont->setCurrentFont(format.font());

    //如果字体大小出错，则选择12
    if(format.fontPointSize() < 9){
        ui->coboxSize->setCurrentIndex(3);
    }
    else{
        ui->coboxSize->setCurrentIndex(ui->coboxSize->findText(QString::number(format.fontPointSize())));
    }

    ui->toolbtnBold->setChecked(format.font().bold());
    ui->toolbtnItalic->setChecked(format.font().italic());
    ui->toolbtnUnderline->setChecked(format.font().underline());
    color = format.foreground().color();
}

//'发送'按钮，发送消息
void QDlgGChat::on_btnSend_clicked()
{
    //获取消息内容
    QString strInfo = ui->txtSend->toHtml();
    if(strInfo.trimmed().isEmpty())
        return;

    //发送消息
    QMsg msg;
    msg.type = MSG_CLIENT_GROUP_CHAT;
    msg.senderID = userid;
    msg.strInfo = strInfo;
    msg.tarIP = QHostAddress(ip).toIPv4Address();
    msg.tarPort = (quint16)port.toUInt()+1;

    //UDP socket套接字发送消息
    udpSocekt.sendMsg(&msg);


    //本地显示
    ui->txtbrosRecv->append(strInfo);
    ui->txtSend->clear();
    ui->txtSend->setFocus();
}

//"关闭"按钮，关闭窗口
void QDlgGChat::on_btnClose_clicked()
{
    close();
}

//字体族
void QDlgGChat::on_coboxFont_currentFontChanged(const QFont &f)
{
    ui->txtSend->setCurrentFont(f);
    ui->txtSend->setFocus();
}

//字体大小
void QDlgGChat::on_coboxSize_currentIndexChanged(const QString &arg1)
{
    ui->txtSend->setFontPointSize(arg1.toDouble());
    ui->txtSend->setFocus();
}

//加粗
void QDlgGChat::on_toolbtnBold_clicked(bool checked)
{
    if(checked){
        ui->txtSend->setFontWeight(QFont::Bold);
    }
    else{
        ui->txtSend->setFontWeight(QFont::Normal);
    }
    ui->txtSend->setFocus();
}

//倾斜
void QDlgGChat::on_toolbtnUnderline_clicked(bool checked)
{
    ui->txtSend->setFontItalic(checked);
    ui->txtSend->setFocus();
}

//下划线
void QDlgGChat::on_toolbtnItalic_clicked(bool checked)
{
    ui->txtSend->setFontUnderline(checked);
    ui->txtSend->setFocus();
}


//颜色
void QDlgGChat::on_toolbtnColor_clicked()
{
    //弹出颜色选择对话框，让用户选择颜色。并放回用户选择的颜色
    color = QColorDialog::getColor(color, this);
    if(color.isValid()){
        ui->txtSend->setTextColor(color);
        ui->txtSend->setFocus();
    }
}

